package com.xh.car.controller;

import com.google.code.kaptcha.Producer;
import com.xh.car.bean.Kaptcha;
import com.xh.car.bean.Userinfo;
import com.xh.car.service.KaptchaService;
import com.xh.car.service.UserinfoService;
import com.xh.car.util.R;
import com.xh.car.util.RTException;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.util.*;

/**
 * @Author PangJunjie
 * @Date 2024/5/7/007
 */
@Controller
public class IndexController {
    @Autowired
    private Producer producer;
    @Autowired
    private KaptchaService kaptchaService;
    @Autowired
    private UserinfoService userinfoService;

    @GetMapping("/kaptcha")
    @ResponseBody
    public R kaptcha() {
        /*获取验证码的文本*/
        String code = producer.createText();
        /*生成UUID*/
        String uuid = DigestUtils.md5Hex(UUID.randomUUID().toString());
        /*设置有效期*/
        Date date = new Date();
        date.setMinutes(date.getMinutes() + 2);
        /*封装数据*/
        Kaptcha kaptcha = new Kaptcha();
        kaptcha.setUuid(uuid);
        kaptcha.setCode(code);
        kaptcha.setExpire(date);
        /*存入数据库*/
        kaptchaService.saveKaptcha(kaptcha);

        /*生成图片验证码*/
        BufferedImage bi = producer.createImage(code);

        // 将验证码图片转换成base64编码的文本格式
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        try {
            ImageIO.write(bi, "jpg", baos);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        String base64Image = Base64.getEncoder().encodeToString(baos.toByteArray());
        Map<String, String> map = new HashMap<>();
        map.put("image", base64Image);
        map.put("uuid", uuid);
        return R.data(map);
    }

    @PostMapping("/login")
    @ResponseBody
    public R login(Userinfo userinfo, Kaptcha kaptcha, HttpSession session) {
        Userinfo loginInfo = userinfoService.login(userinfo, kaptcha);
        session.setAttribute("loginInfo", loginInfo);
        return R.ok();
    }

    @GetMapping("/logout")
    public String logout(HttpServletRequest request) {
        request.getSession().removeAttribute("loginInfo");
        return "redirect:/";
    }

    @GetMapping("/home")
    public String home() {
        return "home";
    }

    @GetMapping("/welcome")
    public String welcome() {
        return "welcome";
    }

    @PostMapping("/upload")
    @ResponseBody
    public R upload(MultipartFile file, HttpServletRequest request, String type) {
        if (file.isEmpty()) {
            return R.error("请选择文件!");
        }
        if (StringUtils.isNotEmpty(type)) {
            type = type + "/";
        }
        /*获取源文件名称*/
        String originalFileName = file.getOriginalFilename();
        /*拆分文件名*/
        String[] os = originalFileName.split("\\.");
        /*获取UUID并转MD5格式作为文件的新名称*/
        String uuid = DigestUtils.md5Hex(UUID.randomUUID().toString());
        /*拼接新文件的名称*/
        String fileName = uuid + "." + os[os.length - 1];
        /*获取年月日用于创建分类文件夹*/
        Date d = new Date();
        int year = d.getYear() + 1900;
        int month = d.getMonth() + 1;
        int date = d.getDate();

        /*获取服务器中项目根目录*/
        String filePath = request.getRealPath("/");
        /*拼接最终存入服务器的文件名*/
        String savePath = "static/upload/" + type + year + "/" + (month < 10 ? "0" + month : month) + "/" + (date < 10 ? "0" + date : date) + "/";
        /*判断该路径是否存在，不存在则创建*/
        File f = new File(filePath + savePath);
        if (!f.exists()) {
            f.mkdirs();
        }
        File uploadFile = new File(filePath + savePath + fileName);
        try {
            file.transferTo(uploadFile);
        } catch (IOException e) {
            throw new RTException(e.getMessage());
        }
        return R.data(savePath + fileName);
    }
}
